package org.bpm.operation
{
	import flash.events.*;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.bpm.events.XMLOperationEvent;
	
	/**
	 * This class will process a preload queue of xml files.
	 * */
	public class XMLOperation extends EventDispatcher
	{
		private var urlQueue:Array;
		private var xmlQueue:Array;
		
		private var urlLoader:URLLoader;
		
		private var isKilled:Boolean;
		
		
		public function XMLOperation(...args)
		{
			super();
			urlQueue = args;
			xmlQueue = new Array();
			
			urlLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, completeHandler);
			urlLoader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			
			
			start();
		}
		private function start():void{
			if(isKilled) return;
			
			var nextUrl:String = urlQueue.shift();
			if(nextUrl){
				loadXML(nextUrl);
			}else{
				finish();
			}
		}
		private function finish():void{
			if(isKilled) return;
			dispatchEvent(new XMLOperationEvent(XMLOperationEvent.XML_READY,xmlQueue));
		}
		private function loadXML(pUrl:String):void{
			urlLoader.load(new URLRequest(pUrl));
		}
		private function progressHandler(pEvent:ProgressEvent):void{
			/**TBD*/
		}
		private function errorHandler(pEvent:IOErrorEvent):void{
			/**TBD*/
		}
		private function completeHandler(pEvent:Event):void{
			var data:XMLList = XMLList(String((pEvent.target as URLLoader).data));
			xmlQueue.push(data);
			start();
		}
		
		public function kill():void{
			isKilled = true;
			
			if(urlLoader){
				urlLoader.removeEventListener(Event.COMPLETE, completeHandler);
				urlLoader.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
				urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				urlLoader = null;
			}
		}
	}
}